<template>
  <admin-layout>
    <!-- 数据卡片 -->
    <div class="data-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card shadow="hover" v-loading="loading.platform">
            <div class="data-card">
              <div class="data-icon users">
                <el-icon><User /></el-icon>
              </div>
              <div class="data-info">
                <div class="data-title">总用户数</div>
                <div class="data-value">
                  <template v-if="loading.platform">
                    <el-skeleton :rows="1" animated />
                  </template>
                  <template v-else>
                    {{ platformStats.totalUsers }}
                  </template>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="6">
          <el-card shadow="hover" v-loading="loading.platform">
            <div class="data-card">
              <div class="data-icon merchants">
                <el-icon><Shop /></el-icon>
              </div>
              <div class="data-info">
                <div class="data-title">总商家数</div>
                <div class="data-value">
                  <template v-if="loading.platform">
                    <el-skeleton :rows="1" animated />
                  </template>
                  <template v-else>
                    {{ platformStats.totalMerchants }}
                  </template>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="6">
          <el-card shadow="hover" v-loading="loading.platform">
            <div class="data-card">
              <div class="data-icon orders">
                <el-icon><Tickets /></el-icon>
              </div>
              <div class="data-info">
                <div class="data-title">总订单数</div>
                <div class="data-value">
                  <template v-if="loading.platform">
                    <el-skeleton :rows="1" animated />
                  </template>
                  <template v-else>
                    {{ platformStats.totalOrders }}
                  </template>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :span="6">
          <el-card
            shadow="hover"
            v-loading="
              loading.platform ||
              loading.merchants ||
              loading.products ||
              loading.riders
            "
          >
            <div class="data-card">
              <div class="data-icon audit">
                <el-icon><Document /></el-icon>
              </div>
              <div class="data-info">
                <div class="data-title">待审核</div>
                <div class="data-value">
                  <template
                    v-if="
                      loading.platform ||
                      loading.merchants ||
                      loading.products ||
                      loading.riders
                    "
                  >
                    <el-skeleton :rows="1" animated />
                  </template>
                  <template v-else>
                    {{
                      platformStats.pendingAudit.merchants +
                      platformStats.pendingAudit.foods +
                      platformStats.pendingAudit.riders
                    }}
                  </template>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 商家审核 -->
    <el-card class="audit-card" shadow="hover" v-loading="loading.merchants">
      <template #header>
        <div class="card-header">
          <span>商家审核 ({{ platformStats.pendingAudit.merchants }})</span>
          <el-button text @click="goToMerchantManagement">查看全部</el-button>
        </div>
      </template>
      <el-table :data="merchantAuditList" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="店铺名称" />
        <el-table-column prop="owner" label="店主" />
        <el-table-column prop="applyTime" label="申请时间" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag
              :type="
                scope.row.status === '待审核'
                  ? 'warning'
                  : scope.row.status === '已通过'
                  ? 'success'
                  : 'danger'
              "
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === '待审核'"
              size="small"
              type="success"
              @click="handleAudit('merchant', scope.row.id, 'approve')"
            >
              通过
            </el-button>
            <el-button
              v-if="scope.row.status === '待审核'"
              size="small"
              type="danger"
              @click="handleAudit('merchant', scope.row.id, 'reject')"
            >
              拒绝
            </el-button>
            <el-button size="small" text>查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="merchantAuditList.length === 0" class="empty-data">
        暂无待审核商家
      </div>
    </el-card>

    <!-- 商品审核 -->
    <el-card class="audit-card" shadow="hover" v-loading="loading.products">
      <template #header>
        <div class="card-header">
          <span>商品审核 ({{ platformStats.pendingAudit.foods }})</span>
          <el-button text @click="goToProductManagement">查看全部</el-button>
        </div>
      </template>
      <el-table :data="foodAuditList" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="商品名称" />
        <el-table-column prop="store" label="所属店铺" />
        <el-table-column prop="price" label="价格">
          <template #default="scope"> ¥{{ scope.row.price }} </template>
        </el-table-column>
        <el-table-column prop="applyTime" label="申请时间" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag
              :type="
                scope.row.status === '待审核'
                  ? 'warning'
                  : scope.row.status === '已通过'
                  ? 'success'
                  : 'danger'
              "
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === '待审核'"
              size="small"
              type="success"
              @click="handleAudit('food', scope.row.id, 'approve')"
            >
              通过
            </el-button>
            <el-button
              v-if="scope.row.status === '待审核'"
              size="small"
              type="danger"
              @click="handleAudit('food', scope.row.id, 'reject')"
            >
              拒绝
            </el-button>
            <el-button size="small" text>查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="foodAuditList.length === 0" class="empty-data">
        暂无待审核商品
      </div>
    </el-card>

    <!-- 骑手审核 -->
    <el-card class="audit-card" shadow="hover" v-loading="loading.riders">
      <template #header>
        <div class="card-header">
          <span>骑手审核 ({{ platformStats.pendingAudit.riders }})</span>
          <el-button text @click="goToRiderManagement">查看全部</el-button>
        </div>
      </template>
      <el-table :data="riderAuditList" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="vehicleType" label="车辆类型">
          <template #default="scope">
            {{ getVehicleTypeLabel(scope.row.vehicleType) }}
          </template>
        </el-table-column>
        <el-table-column prop="applyTime" label="申请时间" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag
              :type="
                scope.row.status === '待审核'
                  ? 'warning'
                  : scope.row.status === '已通过'
                  ? 'success'
                  : 'danger'
              "
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === '待审核'"
              size="small"
              type="success"
              @click="handleAudit('rider', scope.row.id, 'approve')"
            >
              通过
            </el-button>
            <el-button
              v-if="scope.row.status === '待审核'"
              size="small"
              type="danger"
              @click="handleAudit('rider', scope.row.id, 'reject')"
            >
              拒绝
            </el-button>
            <el-button size="small" text>查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="riderAuditList.length === 0" class="empty-data">
        暂无待审核骑手
      </div>
    </el-card>
  </admin-layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import {
  getPlatformStats,
  getMerchants,
  getProducts,
  getRiders,
  reviewStore,
  reviewProduct,
  updateRiderStatus,
} from "@/api";
import { ElMessage } from "element-plus";
import AdminLayout from "@/components/admin/AdminLayout.vue";
import { User, Shop, Tickets, Document } from "@element-plus/icons-vue";

// 定义类型
interface MerchantAudit {
  id: string | number;
  name: string;
  owner: string;
  applyTime: string;
  status: string;
}

interface ProductAudit {
  id: string | number;
  name: string;
  store: string;
  price: number;
  applyTime: string;
  status: string;
}

interface RiderAudit {
  id: string | number;
  name: string;
  phone: string;
  vehicleType: string;
  applyTime: string;
  status: string;
}

// 平台数据
interface PlatformStats {
  totalUsers: number;
  totalMerchants: number;
  totalRiders: number;
  totalOrders: number;
  todayOrders: number;
  weekOrders: number;
  monthOrders: number;
  totalAmount: number;
  todayAmount: number;
  pendingAudit: {
    merchants: number;
    foods: number;
    riders: number;
  };
}

const router = useRouter();

// 平台数据
const platformStats = reactive<PlatformStats>({
  totalUsers: 0,
  totalMerchants: 0,
  totalRiders: 0,
  totalOrders: 0,
  todayOrders: 0,
  weekOrders: 0,
  monthOrders: 0,
  totalAmount: 0,
  todayAmount: 0,
  pendingAudit: {
    merchants: 0,
    foods: 0,
    riders: 0,
  },
});

// 商家审核列表
const merchantAuditList = ref<MerchantAudit[]>([]);

// 商品审核列表
const foodAuditList = ref<ProductAudit[]>([]);

// 骑手审核列表
const riderAuditList = ref<RiderAudit[]>([]);

// 加载状态
const loading = reactive({
  platform: true,
  merchants: true,
  products: true,
  riders: true,
});

// 获取平台统计数据
const fetchPlatformStats = async () => {
  try {
    console.log("开始获取平台统计数据");
    const res = await getPlatformStats();
    console.log("平台统计API响应:", res);

    // 根据响应数据结构获取实际数据
    let data: any = null;
    if (res.data && res.data.data) {
      data = res.data.data;
    } else if (res.data) {
      data = res.data;
    }

    if (data) {
      console.log("平台统计数据:", data);

      // 设置基本统计数据
      platformStats.totalUsers = data.totalUsers || 0;
      platformStats.totalMerchants = data.totalMerchants || 0;
      platformStats.totalRiders = data.totalRiders || 0;
      platformStats.totalOrders = data.totalOrders || 0;
      platformStats.todayOrders = data.todayOrders || 0;
      platformStats.weekOrders = data.weekOrders || 0;
      platformStats.monthOrders = data.monthOrders || 0;
      platformStats.totalAmount = data.totalAmount || 0;
      platformStats.todayAmount = data.todayAmount || 0;

      // 初始化待审核数据
      // 这些数据将在后续的审核列表API中更新
      platformStats.pendingAudit = {
        merchants: 0,
        foods: 0,
        riders: 0,
      };
    } else {
      console.warn("平台统计数据为空或格式不正确");
    }
  } catch (error) {
    console.error("获取平台统计数据失败", error);
    ElMessage.error("获取平台统计数据失败");
  } finally {
    loading.platform = false;
  }
};

// 格式化时间
const formatDate = (dateString: string): string => {
  if (!dateString) return "";
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 获取待审核商家
const fetchPendingMerchants = async () => {
  try {
    console.log("开始获取待审核商家");
    const res = await getMerchants({ status: "PENDING", size: 5 });
    console.log("待审核商家API响应:", res);

    // 尝试多种可能的数据结构
    let data: any = null;
    if (res.data?.content) {
      data = { list: res.data.content, total: res.data.totalElements || 0 };
      console.log("使用res.data.content作为列表数据");
    } else if (res.data?.data?.content) {
      data = {
        list: res.data.data.content,
        total: res.data.data.totalElements || 0,
      };
      console.log("使用res.data.data.content作为列表数据");
    } else if (res.data?.data?.list) {
      data = res.data.data;
      console.log("使用res.data.data.list作为列表数据");
    } else if (res.data?.list) {
      data = res.data;
      console.log("使用res.data.list作为列表数据");
    } else if (Array.isArray(res.data?.data)) {
      data = { list: res.data.data, total: res.data.data.length };
      console.log("使用res.data.data数组作为列表数据");
    } else if (Array.isArray(res.data)) {
      data = { list: res.data, total: res.data.length };
      console.log("使用res.data数组作为列表数据");
    }

    if (data && data.list) {
      merchantAuditList.value = data.list.map((item: any) => ({
        id: item.id,
        name: item.name || item.storeName,
        owner: item.ownerName || item.username || "未知",
        applyTime: formatDate(item.createdAt || item.createTime),
        status: "待审核",
      }));

      // 更新待审核商家数量
      platformStats.pendingAudit.merchants =
        data.total || merchantAuditList.value.length;
      console.log("待审核商家数量:", platformStats.pendingAudit.merchants);
    } else {
      console.warn("待审核商家数据为空或格式不正确");
      merchantAuditList.value = [];
    }
  } catch (error) {
    console.error("获取待审核商家失败", error);
    ElMessage.error("获取待审核商家失败");
    merchantAuditList.value = [];
  } finally {
    loading.merchants = false;
  }
};

// 获取待审核商品
const fetchPendingProducts = async () => {
  try {
    console.log("开始获取待审核商品");
    const res = await getProducts({ status: "PENDING", size: 5 });
    console.log("待审核商品API响应:", res);

    // 尝试多种可能的数据结构
    let data: any = null;
    if (res.data?.content) {
      data = { list: res.data.content, total: res.data.totalElements || 0 };
      console.log("使用res.data.content作为列表数据");
    } else if (res.data?.data?.content) {
      data = {
        list: res.data.data.content,
        total: res.data.data.totalElements || 0,
      };
      console.log("使用res.data.data.content作为列表数据");
    } else if (res.data?.data?.list) {
      data = res.data.data;
      console.log("使用res.data.data.list作为列表数据");
    } else if (res.data?.list) {
      data = res.data;
      console.log("使用res.data.list作为列表数据");
    } else if (Array.isArray(res.data?.data)) {
      data = { list: res.data.data, total: res.data.data.length };
      console.log("使用res.data.data数组作为列表数据");
    } else if (Array.isArray(res.data)) {
      data = { list: res.data, total: res.data.length };
      console.log("使用res.data数组作为列表数据");
    }

    if (data && data.list) {
      foodAuditList.value = data.list.map((item: any) => ({
        id: item.id,
        name: item.name,
        store: item.storeName || "未知店铺",
        price: item.price || 0,
        applyTime: formatDate(item.createdAt || item.createTime),
        status: "待审核",
      }));

      // 更新待审核商品数量
      platformStats.pendingAudit.foods =
        data.total || foodAuditList.value.length;
      console.log("待审核商品数量:", platformStats.pendingAudit.foods);
    } else {
      console.warn("待审核商品数据为空或格式不正确");
      foodAuditList.value = [];
    }
  } catch (error) {
    console.error("获取待审核商品失败", error);
    ElMessage.error("获取待审核商品失败");
    foodAuditList.value = [];
  } finally {
    loading.products = false;
  }
};

// 获取待审核骑手
const fetchPendingRiders = async () => {
  try {
    console.log("开始获取待审核骑手");
    const res = await getRiders({ status: "PENDING", size: 5 });
    console.log("待审核骑手API响应:", res);

    // 尝试多种可能的数据结构
    let data: any = null;
    if (res.data?.content) {
      data = { list: res.data.content, total: res.data.totalElements || 0 };
      console.log("使用res.data.content作为列表数据");
    } else if (res.data?.data?.content) {
      data = {
        list: res.data.data.content,
        total: res.data.data.totalElements || 0,
      };
      console.log("使用res.data.data.content作为列表数据");
    } else if (res.data?.data?.list) {
      data = res.data.data;
      console.log("使用res.data.data.list作为列表数据");
    } else if (res.data?.list) {
      data = res.data;
      console.log("使用res.data.list作为列表数据");
    } else if (Array.isArray(res.data?.data)) {
      data = { list: res.data.data, total: res.data.data.length };
      console.log("使用res.data.data数组作为列表数据");
    } else if (Array.isArray(res.data)) {
      data = { list: res.data, total: res.data.length };
      console.log("使用res.data数组作为列表数据");
    }

    if (data && data.list) {
      riderAuditList.value = data.list.map((item: any) => ({
        id: item.id,
        name: item.name || item.username || item.realName || "未知",
        phone: item.phone || "未知",
        vehicleType: item.vehicleType || "未知",
        applyTime: formatDate(item.createdAt || item.createTime),
        status: "待审核",
      }));

      // 更新待审核骑手数量
      platformStats.pendingAudit.riders =
        data.total || riderAuditList.value.length;
      console.log("待审核骑手数量:", platformStats.pendingAudit.riders);
    } else {
      console.warn("待审核骑手数据为空或格式不正确");
      riderAuditList.value = [];
    }
  } catch (error) {
    console.error("获取待审核骑手失败", error);
    ElMessage.error("获取待审核骑手失败");
    riderAuditList.value = [];
  } finally {
    loading.riders = false;
  }
};

// 获取车辆类型标签
const getVehicleTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    bike: "自行车",
    electric: "电动车",
    motorcycle: "摩托车",
  };
  return typeMap[type] || type;
};

// 审核操作
const handleAudit = async (
  type: string,
  id: string | number,
  action: string
) => {
  try {
    if (type === "merchant") {
      await reviewStore(
        id.toString(),
        action === "approve" ? "APPROVED" : "SUSPENDED"
      );

      // 更新本地数据
      const index = merchantAuditList.value.findIndex((item) => item.id === id);
      if (index !== -1) {
        merchantAuditList.value[index].status =
          action === "approve" ? "已通过" : "已拒绝";
      }

      // 更新统计数据
      platformStats.pendingAudit.merchants -= 1;
      ElMessage.success(
        `商家${action === "approve" ? "审核通过" : "拒绝"}成功`
      );
    } else if (type === "food") {
      await reviewProduct(
        id.toString(),
        action === "approve" ? "APPROVED" : "SUSPENDED"
      );

      // 更新本地数据
      const index = foodAuditList.value.findIndex((item) => item.id === id);
      if (index !== -1) {
        foodAuditList.value[index].status =
          action === "approve" ? "已通过" : "已拒绝";
      }

      // 更新统计数据
      platformStats.pendingAudit.foods -= 1;
      ElMessage.success(
        `商品${action === "approve" ? "审核通过" : "拒绝"}成功`
      );
    } else if (type === "rider") {
      const status = action === "approve" ? "APPROVED" : "SUSPENDED";
      const reason = status === "SUSPENDED" ? "审核不通过" : "";

      await updateRiderStatus(id.toString(), status, reason);

      // 更新本地数据
      const index = riderAuditList.value.findIndex((item) => item.id === id);
      if (index !== -1) {
        riderAuditList.value[index].status =
          action === "approve" ? "已通过" : "已拒绝";
      }

      // 更新统计数据
      platformStats.pendingAudit.riders -= 1;
      ElMessage.success(
        `骑手${action === "approve" ? "审核通过" : "拒绝"}成功`
      );
    }
  } catch (error) {
    console.error(`审核操作失败`, error);
    ElMessage.error(`审核操作失败，请重试`);
  }
};

// 跳转到商家管理
const goToMerchantManagement = () => {
  router.push("/admin/merchants");
};

// 跳转到商品管理
const goToProductManagement = () => {
  router.push("/admin/products");
};

// 跳转到骑手管理
const goToRiderManagement = () => {
  router.push("/admin/riders");
};

onMounted(async () => {
  try {
    // 设置所有加载状态为true
    loading.platform = true;
    loading.merchants = true;
    loading.products = true;
    loading.riders = true;

    // 并行加载所有数据
    await Promise.all([
      fetchPlatformStats(),
      fetchPendingMerchants(),
      fetchPendingProducts(),
      fetchPendingRiders(),
    ]);
  } catch (error) {
    console.error("加载仪表盘数据失败:", error);
    ElMessage.error("加载仪表盘数据失败");
  }
});
</script>

<style scoped>
.data-cards {
  margin-bottom: 20px;
}

.data-card {
  display: flex;
  align-items: center;
}

.data-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.data-icon .el-icon {
  font-size: 24px;
  color: white;
}

.data-icon.users {
  background-color: #1976d2;
}

.data-icon.merchants {
  background-color: #2e7d32;
}

.data-icon.orders {
  background-color: #5e35b1;
}

.data-icon.audit {
  background-color: #ed6c02;
}

.data-title {
  font-size: 14px;
  color: var(--text-secondary);
}

.data-value {
  font-size: 24px;
  font-weight: bold;
  color: var(--text-primary);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.audit-card {
  margin-bottom: 20px;
}

.empty-data {
  text-align: center;
  padding: 30px 0;
  color: var(--text-secondary);
  font-size: 14px;
}
</style>
